import tornado.web
import json
import os
from src.ucloud.read_log_file import read_log_file
from src.parser.xlog_parser import parse_xlog_to_log


class ApiReadFileHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        pass

    def post(self, *args, **kwargs):
        read_file = ''
        json_data = json.loads(self.request.body)
        if json_data is not None:
            parms = json_data['parms']
            if parms is not None:
                read_file = parms['read_file']
            else:
                resp = {'code': 500, 'msg': "parms error"}
                self.write(json.dumps(resp, ensure_ascii=False))
        else:
            resp = {'code': 500, 'msg': "parms error"}
            self.write(json.dumps(resp, ensure_ascii=False))
        read_file_path = read_log_file(read_file)

        file_text = ''
        if read_file_path is not None:
            try:
                ext = read_file_path.split('/')[-1].split('.')[-1]
                if ext == 'log':
                    file_object = open(read_file_path, 'r', encoding='utf-8')
                    try:
                        file_text = file_object.read()
                    finally:
                        file_object.close()
                        os.remove(read_file_path)
                elif ext == 'xlog':
                    # 解析
                    parse_xlog_to_log(read_file_path)
                    file_object = open(read_file_path + '.log', 'r', encoding='utf-8')
                    try:
                        file_text = file_object.read()
                    finally:
                        file_object.close()
                        os.remove(read_file_path)
                        os.remove(read_file_path + '.log')
                else:
                    # jpg ogg wan 等格式
                    pass
            except Exception as e:
                pass

        resp = {'code': 0, 'data': file_text}
        self.write(json.dumps(resp, ensure_ascii=False))
